import BackPage from '@/components/BackPage';
import SaleBadge from '@/components/SaleBadge';
import { addGoods, uploadImageCommodity } from '@/services/commodity';
import { colorStr, getQueryParams } from '@/utils/utils';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Form, Input, message, Modal, Select, Upload } from 'antd';
import type { RcFile, UploadFile } from 'antd/es/upload/interface';
import { useState } from 'react';
import { history } from 'umi';
import { optionEat, optionsUse } from './constants';
import styles from './index.less';

const getBase64 = (file: RcFile): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });

const CreateGoods: React.FC = () => {
  const qs = getQueryParams();
  const [isUploading, setIsUploading] = useState<boolean>(true);
  const { TextArea } = Input;
  const [form] = Form.useForm();
  const [isEat, setIsEat] = useState<boolean>(true);
  const [imgList, setImgList] = useState<any[]>([]);
  const [previewOpen, setPreviewOpen] = useState<boolean>(false);
  const [previewImage, setPreviewImage] = useState<string>('');

  // 初始值
  const getInitValues = () => {
    return {
      ifEat: '食用保健',
    };
  };

  const cascaderChange = (value: string) => {
    if (value === '食用保健') {
      setIsEat(true);
      form.setFieldsValue({ typeUseOne: '', typeUseTwo: '' });
    } else {
      setIsEat(false);
      form.setFieldsValue({ typeEatOne: '', typeEatTwo: '', typeEatThree: '' });
    }
  };

  const uploadButtonUpload = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传照片</div>
    </div>
  );

  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as RcFile);
    }

    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
  };

  const beforeUpload = async (file: RcFile) => {
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('请选择小于2M的图片上传！');
      return Upload.LIST_IGNORE;
    }
    await uploadImageCommodity({
      file,
    }).then((res) => {
      let arr = imgList;
      arr.push({ id: res, fileName: file.name });
      setImgList(arr);
      if (arr.length >= 3) {
        setIsUploading(false);
      }
    });
    return false;
  };

  const confirmSubmit = async (values: any) => {
    try {
      await addGoods(values).then(() => {
        message.success('新建商品成功！');
      });
      history.push({ pathname: '/goodsmanage' });
    } catch (error) {
      console.log(error);
    }
  };

  const onFinish = async () => {
    let values = await form.validateFields();
    values.companyid = qs.id;

    let arr: any[] = [];
    imgList.map((item) => {
      arr.push(item.id);
    });
    values.img = JSON.stringify(arr);

    if (form.getFieldValue('typeUseOne') === undefined) {
      values.typeUseOne = '';
      values.typeUseTwo = '';
    } else {
      values.typeEatOne = '';
      values.typeEatTwo = '';
      values.typeEatThree = '';
    }

    Modal.confirm({
      title: '提交',
      centered: true,
      content: '请确定商品信息无误',
      okText: '确认',
      cancelText: '取消',
      onOk: () => confirmSubmit(values),
    });
  };

  return (
    <BackPage thisRoute={'/creategoods'} lastRoute={'新增商品'}>
      <div className={styles.container}>
        <Form
          className={styles?.formStyle}
          onFinish={onFinish}
          form={form}
          initialValues={getInitValues()}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 28 }}
        >
          <Form.Item
            label="商品标题"
            name="title"
            validateTrigger="onBlur"
            rules={[
              {
                required: true,
                message: (
                  <div>
                    <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                    请输入商品标题
                  </div>
                ),
              },
              {
                pattern: new RegExp(/^[\u4e00-\u9fa5_a-zA-Z0-9]{4,30}$/),
                message: (
                  <div>
                    <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                    请输入4-30个字符（包括中文，英文字母和数字及下划线）
                  </div>
                ),
              },
            ]}
          >
            <Input placeholder="请输入商品标题" autoComplete="off" />
          </Form.Item>
          <Form.Item
            label="商品类型"
            name="ifEat"
            rules={[
              {
                required: true,
                message: (
                  <div>
                    <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                    请选择商品类型
                  </div>
                ),
              },
            ]}
          >
            <Select onChange={cascaderChange}>
              <Select.Option value={'食用保健'}>食用保健</Select.Option>
              <Select.Option value={'器械保健'}>器械保健</Select.Option>
            </Select>
          </Form.Item>
          {(isEat ? optionEat : optionsUse).map((items) => (
            <Form.Item
              label={`${items.label}`}
              name={`${items.name}`}
              key={items.value}
              rules={[
                {
                  required: true,
                  message: (
                    <div>
                      <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                      {`请选择${items.label}`}
                    </div>
                  ),
                },
              ]}
            >
              <Select>
                {items.children.map((item) => (
                  <Select.Option key={item.value} value={`${item.value}`}>
                    {item.label}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
          ))}
          <Form.Item
            label="商品单价"
            name="price"
            validateTrigger="onBlur"
            rules={[
              {
                required: true,
                message: (
                  <div>
                    <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                    请输入商品单价
                  </div>
                ),
              },
              {
                pattern: new RegExp(/^(?:0\.\d{0,1}[1-9]|(?!0)\d{1,5}(?:\.\d{0,1}[1-9])?)$/),
                message: (
                  <div>
                    <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                    请输入正确的价格（小于10W）
                  </div>
                ),
              },
            ]}
          >
            <Input placeholder="请输入商品单价" autoComplete="off" />
          </Form.Item>
          <Form.Item
            label="商品介绍"
            name="detail"
            validateTrigger="onBlur"
            rules={[
              {
                required: true,
                message: (
                  <div>
                    <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                    请输入商品介绍
                  </div>
                ),
              },
              {
                pattern: new RegExp(
                  /[\u4e00-\u9fa5|\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]{2,100}/,
                ),
                message: (
                  <div>
                    <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                    长度需要2-100之间，必须为汉字和中文标点
                  </div>
                ),
              },
            ]}
          >
            <TextArea
              maxLength={100}
              autoComplete="off"
              placeholder="请输入商品介绍"
              //   bordered={false}
              autoSize={{ minRows: 4 }}
              showCount
            />
          </Form.Item>
          <Form.Item
            label="商品图片"
            extra="仅支持jpg.png格式，图片需清晰完整，大小在2M以内，最多上传三张"
            rules={[{ required: true, message: '请上传商品图片' }]}
            className={styles.shopPhoto}
          >
            <Upload
              action="'@/assets/upload'"
              accept=".jpg, .png"
              listType="picture-card"
              onPreview={handlePreview}
              maxCount={3}
              beforeUpload={beforeUpload}
              onRemove={(file) => {
                let arr: any = [];
                let index = 0;
                imgList.map((item) => {
                  if (item.fileName !== file.name || index !== 0) {
                    arr.push(item);
                  } else {
                    index++;
                  }
                });
                if (arr.length < 3) {
                  setIsUploading(true);
                }
                setImgList(arr);
              }}
            >
              {!isUploading ? '' : uploadButtonUpload}
            </Upload>
          </Form.Item>
        </Form>
        <div className={styles.footBtn}>
          <Button type="primary" style={{ backgroundColor: colorStr(5) }} onClick={onFinish}>
            提交
          </Button>
        </div>
        <SaleBadge />
        <Modal
          open={previewOpen}
          title={'商品图片预览'}
          footer={null}
          onCancel={() => {
            setPreviewOpen(false);
          }}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    </BackPage>
  );
};

export default CreateGoods;
